package com.cmy.filter;

import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter {
    //初始化,在web服务器启动就已经初始化了 随时等待监听
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("进入CharacterEncodingFilter init 方法");
    }

    /*
     filterChain 过滤链  (不止一个过滤器)
     1.过滤器中的所有代码,再过滤特定请求时都会执行
     2.必须要让过滤器继续转接,
    */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        System.out.println("CharacterEncodingFilter执行前");
        filterChain.doFilter(req,resp);//将请求继续转接,不写,程序将被拦截停止
        System.out.println("CharacterEncodingFilter执行后");
    }

    //销毁 web服务器关闭时销毁
    public void destroy() {
        System.out.println("CharacterEncodingFilter 销毁");
    }
}

    